package com.liuzh.fitnessplan.broadcast

import android.app.*
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Context.NOTIFICATION_SERVICE
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Build
import android.util.Log
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.room.Room
import com.liuzh.fitnessplan.R
import com.liuzh.fitnessplan.database.bean.TimePlans
import com.liuzh.fitnessplan.tools.RoomDatabaseUtil

class AlarmReceiver() : BroadcastReceiver() {
    @RequiresApi(Build.VERSION_CODES.O)
    override fun onReceive(context: Context?, intent: Intent?) {
        showNotification(context , intent!!.getIntExtra("id",0))
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun showNotification(context: Context?,id : Int) {
        val channel_ID = "1"
        val channel_Name = "sport_name"
        var timePlans : TimePlans
        val notificationManager = context?.getSystemService(NOTIFICATION_SERVICE) as NotificationManager

        val ntChannel = NotificationChannel(channel_ID,channel_Name,NotificationManager.IMPORTANCE_HIGH)
        notificationManager.createNotificationChannel(ntChannel)

        Thread {
            timePlans = RoomDatabaseUtil.instance.getDatabase(context).timeDao().getSingleData(id)
            val notification = NotificationCompat.Builder(context,"Alarm")
                .setContentTitle("运动提醒")
                .setContentText("您的${timePlans.title}项目该开始了 运动:${timePlans.project}")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(context.resources,R.mipmap.ic_launcher))
                .setChannelId(channel_ID)
                .setAutoCancel(true)
                .build()
            notificationManager.notify(1,notification)
            timePlans.isOpen = false

            if(timePlans.repeat == "everyday"){
                val intent = Intent("com.liuzh.ALARM_BROADCAST")
                intent.putExtra("id",id)
                val pendingIntent = PendingIntent.getBroadcast(context,1,intent, PendingIntent.FLAG_CANCEL_CURRENT)
                val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
                alarmManager.setExact(AlarmManager.RTC_WAKEUP,System.currentTimeMillis()+3600*1000*24,pendingIntent)
                timePlans.isOpen = true
            }
            RoomDatabaseUtil.instance.getDatabase(context).timeDao().update(timePlans)
            val intent = Intent("com.liuzh.UPDATE_UI")
            context.sendBroadcast(intent)
        }.start()

    }


}